<template>
  <div>
    <div ref="map" id="map" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      markers: [],
      tmap: null,
      cityMap: null,
      lastInfoBox: "",
    };
  },
  props: {
    // baseTable: {},
    sContent: {},
    carFrame: {
      type: Function,
    },
    clickbMapData: {},
  },
  computed: {
    // // 区域监听
    // cityData() {
    //   return this.$store.state.areaSearchCar;
    // },
    // // 公司监听
    // companyListData() {
    //   return this.$store.state.companySearchCar;
    // },
  },
  watch: {
    companyListData(val) {
      console.log(val, "=====companyListData");
      this.companyDataMap(val);
    },
    // cityData(val) {
    //   console.log(val, "=====cityData");
    //   this.cityDataMap(val);
    // },
    clickbMapData: {
      deep: true,
      handler(val) {
        if (val) {
          this.clickbMap(val);
        }
      },
    },
    // baseTable: {
    //   deep: true,
    //   handler(val) {
    //     if (!val) {
    //       this.cityMap.centerAndZoom(new T.LngLat(104.087715, 30.567811), 5);
    //     }
    //   },
    // },
  },
  mounted() {
    this.loadTiandituScript()
      .then(() => {
        console.log("初始化地图");
        this.initMap(); // 脚本加载后初始化地图
      })
      .catch((error) => {
        console.error("Failed to load Tianditu API script:", error);
      });
  },
  // mounted() {
  //   this.initMap();
  //   this.initbCitymap();
  // },
  methods: {
    // 动态加载天地图脚本
    loadTiandituScript() {
      return new Promise((resolve, reject) => {
        if (typeof T !== "undefined") {
          resolve(); // 如果 T 已经存在，直接 resolve
        } else {
          const script = document.createElement("script");
          script.src =
            // "http://api.tianditu.gov.cn/api?v=4.0&tk=33752fcceac2cec91dcd788b342fba06";
            "https://gis.soszyzg.com/tdtapi?v=4.0&tk=33752fcceac2cec91dcd788b342fba06";
          script.onload = resolve;
          script.onerror = reject;
          document.head.appendChild(script);
        }
      });
    },
    initMap() {
      console.log("initMap==");
      this.tmap = new T.Map("map", {
        attributionControl: false,
        inertia: false,
      });
      this.tmap.centerAndZoom(new T.LngLat(104.087715, 30.567811), 12);
      this.tmap.enableScrollWheelZoom(true);
      this.tmap.enableInertia(true);
    },

    clickbMap(val) {
      console.log("clickbMap==", val);
      this.carFrame(val); // 执行点击后的逻辑
      var mapT = this.tmap;
      var pt = new T.LngLat(val.lng, val.lat);
      mapT.centerAndZoom(pt, 13); //

      // 创建新的 InfoWindow
      var infoBox = new T.InfoWindow(this.sContent, {
        offset: new T.Point(0, -30), // 设置偏移量
        maxWidth: 200,
      });

      // 打开新的弹窗
      mapT.openInfoWindow(infoBox, pt);
    },

    TmapSetClusterMraker(val) {
      console.log(1231, val);
      var that = this;
      if (val.length > 0) {
        if (this.markers.length > 0) {
          this.clearMarkers();
          // this.markerClusterer.clearMarkers();
        }
        this.markers = [];
        val.forEach((e, i) => {
          let pt = new T.LngLat(e.lng, e.lat);
          // 设置自定义图标
          let icon = new T.Icon({
            iconUrl: e.defaultIcon
              ? e.defaultIcon
              : "https://gis.soszyzg.com/tdtimages/bus/start.png", // 设置图标 URL
            iconSize: new T.Point(50, 50), // 图标大小
            iconAnchor: new T.Point(25, 50), // 图标锚点
          });
          let marker = new T.Marker(pt, { icon: icon });
          if (!marker) {
            console.error("Marker creation failed.");
          }
          let label = new T.Label({
            text: e.hbCarNo,
            position: pt,
            offset: new T.Point(-50, -65),
          });
          if (!label) {
            console.error("Label creation failed.");
          }
          try {
            if (this.tmap && marker) {
              this.tmap.addOverLay(marker);
            }
            if (this.tmap && label) {
              this.tmap.addOverLay(label);
            }
          } catch (error) {
            console.error("Error in adding overlay:", error);
          }
          //设置显示地图的中心点和级别
          if (i == 0) {
            this.tmap.centerAndZoom(new T.LngLat(val[0].lng, val[0].lat), 5);
          }

          marker.addEventListener("click", function () {
            // 自定义弹窗逻辑
            that.carFrame(e);
            console.log(that.sContent, "sContent");

            // 创建自定义信息窗口
            let infoBox = new T.InfoWindow(that.sContent, {
              offset: new T.Point(0, -30),
              closeOnClick: true, //允许点击地图关闭窗口
              closeButton: false, //是否显示关闭按钮
            });

            // // 如果有之前的自定义窗口，关闭它
            // if (that.lastInfoBox) {
            //   that.lastInfoBox.close();
            // }

            // 关闭天地图可能自动弹出的默认 InfoWindow
            that.tmap.closeInfoWindow(); // 检查是否有这样的方法

            // 保存并显示自定义的 InfoWindow
            that.lastInfoBox = infoBox;
            that.tmap.openInfoWindow(infoBox, pt);
          });

          this.markers.push(marker);
        });

        if (this.markerClusterer) {
          this.markerClusterer.clearMarkers();
        }
        this.markerClusterer = new T.MarkerClusterer(this.tmap, {
          markers: this.markers,
        });
        this.tmap.addEventListener("load", () => {
          // 确保地图加载完毕后添加标记
          this.markerClusterer.addMarkers(this.markers);
        });
      } else {
        this.clearMarkers();
      }
    },
    cityDataMap(val) {
      var that = this;
      if (val.length > 0) {
        // 清除之前的标记和聚合点
        if (this.markers.length > 0) {
          this.clearMarkers(); // 清除之前的标记
        }
        this.markers = [];
        val.forEach((e) => {
          var pt = new T.LngLat(e.lng, e.lat); //  Latitude改为lng
          // 设置自定义图标
          var icon = new T.Icon({
            iconUrl: e.defaultIcon, // 设置图标 URL
            iconSize: new T.Point(50, 50), // 图标大小
            iconAnchor: new T.Point(25, 50), // 图标锚点
          });

          var marker = new T.Marker(pt, { icon: icon }); // 创建带有图标的标记
          if (!marker) {
            console.error("Marker creation failed.");
          }
          // 创建自定义 label（使用 T.Label）
          var label = new T.Label({
            text: e.hbCarNo,
            position: pt,
            offset: new T.Point(-50, -65),
          });

          try {
            if (this.cityMap && marker) {
              this.cityMap.addOverLay(marker);
            }
            if (this.cityMap && label) {
              this.cityMap.addOverLay(label);
            }
          } catch (error) {
            console.error("Error in adding overlay:", error);
          }
          marker.addEventListener("click", function () {
            that.carFrame(e); // 执行点击后的操作
            console.log(that.sContent, "sContent");
            var infoBox = new T.InfoWindow(that.sContent, {
              offset: new T.Point(0, -30), // 设置偏移量
              closeOnClick: true,
              closeButton: false,
            });

            // 打开新的弹窗
            that.cityMap.openInfoWindow(infoBox, pt);
          });
          // 将标记添加到 markers 数组
          this.markers.push(marker);
        });

        if (this.markerClusterer) {
          this.markerClusterer.clearMarkers();
        }
        this.markerClusterer = new T.MarkerClusterer(this.cityMap, {
          markers: this.markers,
        });
        this.cityMap.addEventListener("load", () => {
          // 确保地图加载完毕后添加标记
          this.markerClusterer.addMarkers(this.markers);
        });
      } else {
        this.clearMarkers(); // 如果没有标记，清除地图上的所有标记
      }
    },
    clearMarkers() {
      if (this.markerClusterer) {
        this.markerClusterer.clearMarkers();
      }
      this.tmap.clearOverLays();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .tdt-infowindow-content {
  margin: 0 !important;
}
</style>
